<template>
  <div style="display: flex">
    <!-- <category-panel title="商品分类" icon="tree" request="productCategory" @delClick="delClick" @notClick="notClick"
      @nodeClick="nodeClick"></category-panel> -->
    <el-container>
      <div style="padding: 10px;padding-bottom: 0">
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <div style="display: flex;flex-direction: row;justify-content: space-between;width: 100%;">
            <div style="display: flex;align-items: center">
              <div class="report_header_query"  style="width:90px;">
                <el-select v-model="value" placeholder="状态" clearable>
                  <el-option label="未上架" :value="false"></el-option>
                  <el-option label="已上架" :value="true"></el-option>
                </el-select>
              </div>
              <div class="report_header_query"  style="width:90px;">
                <el-select v-model="query.tagId" placeholder="标签" clearable>
                  <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </div>
            </div>
            <div style="display: flex">

              <div class="report_header_date">
                <el-input prefix-icon="el-icon-search" placeholder="商品名称/货号/条码" v-model="query.keyword" clearable></el-input>
              </div>
              <el-button style="margin-left: 10px;margin-top: 7px;" size="small" type="primary" @click="queryClick">查询</el-button>
              <!--<el-button style="margin-left: 10px;margin-top: 7px;height: 32px" v-permission="['pledge.add']" size="small"-->
                <!--type="primary" @click="addClick">新增-->
              <!--</el-button>-->
              <el-button style="margin-left: 10px;margin-top: 7px;" size="small" type="primary" @click="showDialog" v-permission="['waterTicket.add']">新增</el-button>
              <el-button type="warning"  size="small"  style="margin-left: 10px;margin-top: 7px;" @click="onBatchAddPledge">一键添加空桶</el-button>

            </div>
          </div>
        </div>
      </div>
      <div class="pd10">
        <el-table :data="productData" border stripe :height="curHeight" @sort-change="sortChange" ref="table"
          v-loadMore="[payLoads,'product-list']" tooltip-effect="dark" @selection-change="handleSelectionChange"
          :row-key="getRowKeys">
          <el-table-column label="缩略图" width="72">
            <template slot-scope="{row}">
              <img :src="row.thumbnail" style="width: 50px; height: 50px; vertical-align:middle; overflow: hidden;"></img>
            </template>
          </el-table-column>
          <el-table-column label="名称" align="left" min-width="250" prop="name" sortable="custom">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.subType">{{ scope.row.subType | watchSubType }}</el-tag>
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分类" width="80" align="center" prop="productCategoryName"></el-table-column>
          <el-table-column label="空桶" width="90" align="center" prop="price" sortable="custom"></el-table-column>
          <el-table-column label="状态" width="80" align="center" prop="isMarketable">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isMarketable ?'primary':'danger'">
                <span>{{ scope.row.isMarketable | watchType }}</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" width="70" prop="orders" :render-header="ordersIcons">
            <template slot-scope="scope">
              <el-input v-model="scope.row.orders" @blur="bulrOrders(scope.row)"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="功能" fixed="right" width="80" align="center">
            <template slot-scope="scope" >
              <el-tooltip class="item" effect="dark" content="下架" placement="top-start" v-permission="['pledge.down']" >
                <el-button v-if="scope.row.isMarketable"  @click="releaseProduct(scope.row)" :type="scope.row.isMarketable ?'primary':'danger'" size="mini">下架</el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="上架" placement="top-start" v-permission="['pledge.up']">
                <el-button v-if="!scope.row.isMarketable"   @click="releaseProduct(scope.row)" :type="scope.row.isMarketable ?'primary':'danger'" size="mini">上架</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="70" align="center">
            <template slot-scope="scope">
              <div v-show="deleted == false">
                <el-tooltip v-permission="['pledge.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                  <a @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit"></i>
                  </a>
                </el-tooltip>
                <el-tooltip v-permission="['pledge.delete']" class="item" effect="dark" content="删除" placement="top-start">
                  <a style="margin-left: 10px" @click="deleteProduct(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete"></i>
                  </a>
                </el-tooltip>

              </div>
              <el-tooltip class="item" v-permission="['pledge.del']" effect="dark" content="恢复商品" v-show="deleted == true"
                placement="top-start">
                <a style="margin-left: 10px" @click="restoreProduct(scope.row)">
                  <i style="color: #E6A23C" class="el-icon-refresh-right"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadProduct"></pagination>
      </el-footer>



      <el-dialog width="450px" title="添加空桶" :visible.sync="addFormVisible">
        <el-form ref="addFormRef" style="margin: 30px 0;" :model="addForm" :rules="addFormRules" label-width="80px">
          <el-form-item prop="productId" label="桶装水">
            <search-options ref="optionsRef" :tips-text="'请选择桶装水'" :options-style="'width: 80%'" :request="'product'" :fixed-params="addFixedParams" @getValue="addQueryProduct" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addFormVisible = false">取 消</el-button>
          <el-button v-permission="['waterTicket.add']" :loading="addClicked" type="primary" @click="addClick">确 定</el-button>
        </div>
      </el-dialog>

    </el-container>

  </div>
</template>
<script>

  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {
    list,
    del
  } from '@/api/product'

  import {addPledge, batchAddPledge } from '@/api/pledge'
  import searchOptions from '@/components/searchOptions'

  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import utils from '../../utils/utils.js'

  import {
    EventBus
  } from '@/api/eventBus'

  import Pagination from '@/components/Pagination'
  import loadMore from '@/utils/loadMore.js'
  import {
    list as tagList
  } from '@/api/tag'

  export default {
    name: 'product-list',
    directives: {
      permission,
      loadMore,
      elDragDialog
    },
    data() {
      return {
        tags: [], //标签列表
        procudtDate: [],
        value: '',
        times: '',
        productData: [],
        pageNum: 1,
        pageSize: 20,
        total: 0,
        queryType: true,
        query: {
          tagId: '',
          keyword: ''
        },
        keyword: {
          tagId: '',
          keyword: ''
        },
        curHeight: null,
        excelData: [],
        deleted: false,
        direction: '',
        sortField: '',
        payLoads: '',
        addFixedParams: {
          'type': 0,
          'isList': true,
        },
        addForm: {
          productId: '',
          productCategoryId: ''
        },

        addFormRules: {
          productId: [
            { required: true, message: '请选择商品名称', trigger: 'blur' }
          ],
          productCategoryId: [
            { required: true, message: '请选择商品分类', trigger: 'change' }
          ]
        },
        addFormVisible: false,
      }
    },
    components: {
      Pagination,searchOptions
    },

    created() {
      this.times = new Date().getSeconds()
      this.loadTag()
      var _this = this
      this.loadProduct()
      EventBus.$on('product-productExport', res => {
        this.loadProduct()
      })
      EventBus.$on('pledge-add', res => {
        // 更新列表数组
        _this.productData.splice(0, 0, res)
      })
      EventBus.$on('pledge-edit', res => {
        // 监听新增完毕
        // 更新列表数组
        for (var i = 0; i < _this.productData.length; i++) {
          if (_this.productData[i].id == res.id) {
            this.$set(this.productData, i, res)
          }
        }
      })
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    filters: {
      watchSubType(val) {
        if (val == 0) {
          return '产品'
        } else if (val == 1) {
          return '套餐'
        } else if (val == 2) {
          return '水票'
        } else if (val == 3) {
          return '空桶'
        } else if (val == 4) {
          return '空桶'
        }
      },
      watchType(val) {
        if (val === false) {
          return '未上架'
        } else if (val === true) {
          return '已上架'
        }
      },
      watchPublished(val) {
        if (val == 0) {
          return '已创建'
        } else if (val == 1) {
          return '申请中'
        } else if (val == 2) {
          return '已上架'
        } else if (val == 3) {
          return '已下架'
        }
      },
      watchShare(val) {
        if (!val) {
          return '已禁用'
        } else {
          return '已启用'
        }
      }
    },
    activated() {
      this.payLoads = new Date().getTime()
    },
    methods: {
      onBatchAddPledge(){
        batchAddPledge().then(res=>{
          if(res.type='success'){
            this.$message('一键添加成功');
            this.loadProduct()
          }else{
            this.$message({
              message: '一键添加失败',
              type: 'warning'
            });
          }
        })
      },
      loadTag() {
        let params = new URLSearchParams()
        params.append('type', '3')
        tagList(params).then(res => {
          this.tags = res.data.data
        })
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h =
                document.documentElement.clientHeight ||
                document.body.clientHeight
              _this.curHeight = h - 266 //减去页面上固定高度height
            } else {
              var h =
                document.documentElement.clientHeight ||
                document.body.clientHeight
              _this.curHeight = h - 220 //减去页面上固定高度height
            }
          })()
        }
      },
      comeIn() {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220 //减去页面上固定高度height
      },
      editClick(row) {
        this.$router.push({
          path: '/pledge/edit',
          query: {
            id: row.id
          }
        })
      },
      addQueryProduct(value) { // 添加的查询商品
        this.addForm.productId = value
      },
      showDialog() {
        this.addFormVisible = true
      },
      loadProduct() {
        var _this = this
        let params = new URLSearchParams()
        params.append('pageNum', _this.pageNum)
        params.append('pageSize', _this.pageSize)
        params.append('keyword', _this.keyword.keyword)
        params.append('isList', true)
        params.append('noSubType2', true)
        params.append('tagIds', this.keyword.tagId)
        params.append('deleted', _this.deleted)
        params.append('sortField', _this.sortField)
        params.append('direction', _this.direction)
        params.append('isMarketable', this.value)
        params.append('subType', 3)
        list(params)
          .then(response => {
            console.log(response)
            _this.productData = response.data.data
            _this.total = response.data.total
          })
          .catch(error => {
            console.log('error!!')
          })
      },

      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h =
            document.documentElement.clientHeight || document.body.clientHeight
          this.curHeight = h - 266 //减去页面上固定高度height
        } else {
          var h =
            document.documentElement.clientHeight || document.body.clientHeight
          this.curHeight = h - 220 //减去页面上固定高度height
        }
      },

      addClick() { // 新增
        this.$refs['addFormRef'].validate((valid) => {
          if (valid) {
            this.addClicked = true
            addPledge({ productId: this.addForm.productId, productCategoryId: this.addForm.productCategoryId }).then(res => {
              this.loadProduct()
              this.addFormVisible = false
              this.addClicked = false
            }).catch(() => { this.addClicked = false })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

//      addClick() {
//        this.$router.push({
//          path: '/pledge/add'
//        })
//      },
      infoClick(row) {
        this.$router.push({
          path: '/product/index',
          query: {
            id: row.id,
            goods: row.goodsId
          }
        })
      },
      deleteProduct(data) {
        console.log(data)
        var _this = this
        this.$confirm('确认删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            del(data.id)
              .then(response => {
                console.log(response)
                if (response.type)
                // 更新列表数组
                {
                  _this.productData.forEach(function(item, index) {
                    if (item.id == data.id) {
                      _this.productData.splice(index, 1)
                    }
                  })
                }
              })
              .catch(error => {
                console.log('error!!')
              })
          })
          .catch(() => {})
      },
      queryClick() {
        this.keyword = this.query
        this.pageNum = 1
        this.loadProduct()
      },
      resetClick() {
        this.value = ''
        this.query.keyword = ''
        this.query.tagId = ''
        this.query.supplierId = ''
        this.keyword = this.query
        this.pageNum = 1
        this.loadProduct()
      },
      handleDownload() {
        this.$router.push({
          path: '/product/productExport'
        })
      },
      notClick() {
        this.productCategory = 0
        this.deleted = false
        this.loadProduct()
      },
      delClick() {
        this.deleted = true
        this.productCategory = ''
        this.loadProduct()
      },
      nodeClick(data) {
        this.deleted = false
        this.productCategory = data.id
        this.loadProduct()
      },
      releaseProduct(row) {
        this.$confirm(row.isMarketable ? '确认下架?' : '确认上架', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            updateProduct({
                id: row.id,
                isMarketable: row.isMarketable ? false : true
              })
              .then(response => {
                console.log(response)
                this.$message({
                  message: '设置成功',
                  offset: 120,
                  center: true
                })
                // 更新列表数组
                for (var i = 0; i < this.productData.length; i++) {
                  if (this.productData[i].id == response.data.id) {
                    this.productData[i].isMarketable = response.data.isMarketable
                  }
                }
              })
              .catch(error => {
                console.log('error!!')
              })
          })
          .catch(() => {})
      },
      restoreProduct(row) {
        var _this = this
        console.log(row)
        this.$confirm('确认恢复?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            updateProduct({
                id: row.id,
                deleted: false,
                isMarketable: false
              })
              .then(response => {
                // 更新列表数组
                _this.productData.forEach(function(item, index) {
                  if (item.id == row.id) {
                    _this.productData.splice(index, 1)
                  }
                })
              })
              .catch(error => {
                console.log('error!!')
              })
          })
          .catch(() => {})
      },
      // 表格排序
      sortChange(column) {
        console.log(column)
        this.sortField = column.prop
        if (column.order == 'ascending') {
          this.direction = 'asc'
        } else {
          this.direction = 'desc'
        }
        this.loadProduct()
      },
      ordersIcons(h, {
        column
      }) {
        const inReview = '点击下方数字区域可直接更改排序。'
        return h('div', [
          h('span', column.label),
          h(
            'el-tooltip', {
              props: {
                placement: 'top'
              }
            },
            [
              h(
                'div', {
                  slot: 'content',
                  style: {
                    width: '200px',
                    whiteSpace: 'normal',
                    'margin-bottom': '10px'
                  }
                },
                inReview
              ),
              h('i', {
                class: 'el-icon-question',
                style: 'color:#888888;margin-left:5px;position:absolute'
              })
            ]
          )
        ])
      },
      bulrOrders(data) {
        console.log(data)
        let _this = this
        updateProduct({
            id: data.id,
            orders: data.orders,
            isMarketable: data.isMarketable
          })
          .then(response => {})
          .catch(error => {
            console.log('error!!')
          })
      },
      handleSelectionChange(data) {
        var _this = this
        console.log(data)
        _this.procudtDate = []
        data.forEach(function(item) {
          var id = item.id
          _this.procudtDate.push(id)
        })
        console.log(_this.procudtDate)
      },
      getRowKeys(row) {
        return row.id // id为列表数据的唯一标识
      },
      handleCommand(data) {
        console.log(data)
        var _this = this
        if (data == 'mobile') {
          // this.movingGoodsTyep = true
          this.$refs.movingGoods.show()
        } else if (data == 'del') {
          this.$confirm('是否确认删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            _this.totalDelClick()
          }).catch(() => {

          })
        } else if (data == 'shelves') {
          this.shelvesClick()
        } else if (data == 'theShelves') {
          this.theShelvesClick()
        } else if (data == 'Import') {
          this.handleDownload()
        } else if (data == 'copy') {
          this.copyProductClick()
        }
      },
      productListClick() {
        this.loadProduct()
        this.toggleSelection()
      },
      totalDelClick() {
        var _this = this
        var procudtDate = ''
        for (let i = 0; i < _this.procudtDate.length; i++) {
          if (i < _this.procudtDate.length - 1) {
            procudtDate += _this.procudtDate[i] + ','
          } else {
            procudtDate += _this.procudtDate[i]
          }
        }
        del(procudtDate).then(response => {
          _this.$message({
            type: 'info',
            message: response.content
          })
          _this.loadProduct()
          _this.toggleSelection()
        }).catch(error => {

        })
      },
      toggleSelection() {
        this.$refs.table.clearSelection()
      },
      shelvesClick() {
        var _this = this
        this.$confirm('是否确认上架, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var productForm = []
          console.log('1111')
          _this.procudtDate.forEach(function(item) {
            var product = {
              id: item,
              isMarketable: true
            }
            productForm.push(product)
          })
          BatchUpdate(productForm).then(response => {
            console.log(response)
            _this.$message({
              type: 'success',
              message: response.content
            })
            _this.loadProduct()
            _this.toggleSelection()
          }).catch(error => {})
        }).catch(() => {

        })

      },
      theShelvesClick() {
        var _this = this
        this.$confirm('是否确认下架, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var productForm = []
          console.log('1111')
          _this.procudtDate.forEach(function(item) {
            var product = {
              id: item,
              isMarketable: false
            }
            productForm.push(product)
          })
          BatchUpdate(productForm).then(response => {
            console.log(response)
            _this.$message({
              type: 'success',
              message: response.content
            })
            _this.loadProduct()
            _this.toggleSelection()
          }).catch(error => {})
        }).catch(() => {

        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #f2f2f2;
  }

  .elOption {
    background-color: #909399;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 50%;
    height: 40px
  }

  .tags {
    width: 33.33%;
    text-align: left;
    padding-bottom: 5px;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/ .el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }

  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }

  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
